package com.project.picxg.controller;

import com.project.picxg.entity.Image;
import com.project.picxg.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ImageController {
    @Resource
    private StorageService storageService;

    @RequestMapping("/upload")
    @ResponseBody
    public ModelMap upload(@RequestParam(value = "image", required = true) MultipartFile imageFile) {
        ModelMap map = new ModelMap();
        String name = new String();
        try {
            name = storageService.upload(imageFile.getInputStream(), imageFile.getOriginalFilename());
        } catch (Exception e) {
            map.put("error", "Error:" + e.getMessage());
        }
        if (name != null) {
            map.put("success",  name);
        } else {
            map.put("error", "Failed to upload");
        }
        return map;
    }

    //查看资源
    @RequestMapping(value = "/getImage/{filename}" , method = RequestMethod.GET)
    public ResponseEntity getImage(@PathVariable String filename) {
        HttpHeaders headers = new HttpHeaders();
        try {
            Image url = storageService.getUrl(filename);
            //向headers内添加Content-type，支持视频，图片，音频等

            switch (filename.substring(filename.lastIndexOf(".") + 1)) {
                case "mp4":
                    headers.setContentType(MediaType.valueOf("video/mp4"));
                    break;
                default:
                    headers.setContentType(MediaType.valueOf("image/png"));
                    break;
            }
            FileInputStream inputStream = new FileInputStream(url.getPath());
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return new ResponseEntity<Object>(bytes, headers, HttpStatus.OK);
        }catch (Exception e){
            //设置Content-type为application/json
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 500);
            resultMap.put("message", "not found");
            return new ResponseEntity<Object>(resultMap, headers, HttpStatus.OK);
        }
    }

}
